<?php
namespace app\admin\controller;
use app\admin\model\User;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;
/*登录*/
class Login extends Controller{


    public function index(){
        $user=Session::get('user_id');

        if (!empty($user)){
            //判断是否有session，如果已经登陆过那么直接跳转至首页防止重复登陆
            return $this->fetch('admin@index/index',[
                'os'=>PHP_OS,
                'yxhj'=>$_SERVER["SERVER_SOFTWARE"],
                'php_version'=>PHP_VERSION,
                'db_version'=>Db::query('select VERSION() as db_version')[0]['db_version'],
                'server_ip'=>GetHostByName($_SERVER['SERVER_NAME']),
                'language'=>$_SERVER['HTTP_ACCEPT_LANGUAGE'],
                'host'=>$_SERVER['SERVER_PORT'],
                'time'=>date("Y-m-d H:i:s"),
                'user'=>$user
            ]);
        }else{

            return $this->fetch();//如果没有session那么就要登陆
        }
    }


    public function login(Request $request)
    {

        if ($this->request->isPost()){


            $captcha_code=input('captcha_code');
            if (!captcha_check($captcha_code)){//验证码错误
                $fh=[
                    'code'=>-1,
                    'message'=>'验证码错误'
                ];
            }
            else{
                //验证码正确情况下判断用户名和密码是否存在

                $Dbuser=new User();
                $result=$Dbuser->index(input('username'),input('password'));

                if ($result['code']>=1){
                    $fh=[
                        'code'=>1,
                    ];
                }else if ($result['code']==-2){
                    $fh=[
                        'code'=>-2,
                        'message'=>'用户名不存在'
                    ];
                }else if ($result['code']==-3){
                    $fh=[
                        'code'=>-3,
                        'message'=>'密码错误'
                    ];
                }

            }

        }else{

            return $this->fetch('index');
        }
        if ($fh['code']>0){
            Session::set('user_id',$result['code']);//登录成功就创建session
        }



        $fh=json_encode($fh);
        return  $fh;

    }



    //退出登录
    public function quit(){

        Session::delete('user_id');//删除session
        $this->redirect('admin/login/index');
    }


}
